package com.zzl.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zzl.entity.Grade;
import com.zzl.entity.PageBean;
import com.zzl.services.GradeServices;
import com.zzl.services.impl.GradeServicesImpl;
import com.zzl.util.DbUtil;
import com.zzl.util.JsonUtil;
import com.zzl.util.ResponseTypeUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

public class GradeListServlet extends HttpServlet {
    DbUtil dbUtil=new DbUtil();
    GradeServices gradeService=new GradeServicesImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page=req.getParameter("page");
        String rows=req.getParameter("rows");
        String gradeName=req.getParameter("gradeName");
        if(gradeName==null){
            gradeName="";
        }
        Grade grade=new Grade();
        grade.setGradeName(gradeName);
        PageBean pageBean=new PageBean();
        pageBean.setPage(Integer.parseInt(page));
        pageBean.setRows(Integer.parseInt(rows));

        Connection con=null;

        try {
            con=dbUtil.getCon();
            JSONObject result=new JSONObject();
            JSONArray jsonArray= JsonUtil.formatRsToJsonArray(gradeService.gradeList(con, pageBean, grade));
            int total=gradeService.gradeaCount(con,grade);
            result.put("rows",jsonArray);
            result.put("total",total);
            ResponseTypeUtil.write(resp,result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
